// pages/study/study.js
var util = require('../../utils/util.js')
var list2 = require('../../data/cet4.js')
var list3 = require('../../data/cet6.js')
var list4 = require('../../data/kaoyan.js')
var list5 = require('../../data/cet4_import.js')
var list6 = require('../../data/cet6_import.js')
var list7 = require('../../data/kaoyan_import.js')
const db = wx.cloud.database();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    id: 0,
    day_num: 0,
    all_num: 0,
    word_record: [],
    collection: [],
    now_num: 0,
    //获取时间
    time: "",
    username: [],
    // 判断是否为第一次加载本页面
    count: 0,
    day_word: [],
    // 是否隐藏复习地提示窗
    show_review:true,
    // 进入页面的次数
    inint_num:0,
    // 
    times:true,
  },

  tosearch: function () {
    wx.navigateTo({
      url: '../search/search',
    })
  },

  tojobs: function () {
    if (!wx.getStorageSync('checked') || !wx.getStorageSync('dayNum')){
      if(this.data.times){
        this.popup.showPopup();
      }
      this.setData({
        times:false,
      })
    }else{
    if (this.data.all_num >= this.data.word_record.length && this.data.word_record != '') {
      wx.navigateTo({
        url: '../logs/logs',
      })
    } else {
      wx.navigateTo({
        url: '../jobs/jobs',
      })
    }
    }
  },
  // 跳转到复习界面
  toreview: function () {
    if(!wx.getStorageSync('checked')){
        this.setData({
          show_review:false,
        })
    }else{
      wx.navigateTo({
        url: '../review/review',
      })
    }

  },
// 隐藏复习提示弹窗
  hide_review:function(){
    this.setData({
      show_review:true,
    })
  },

  
 tobar:function(){
    wx.navigateTo({
      url:'../bar/bar',
    })
 },
  /**
   * 生命周期函数--监听页面加载
   */
   onLoad:function  () {
    console.log("kaishi ")
    let that=this
    // this.setData({inint_num:wx.getStorageSync("init_num") })
    // console.log("init_num----------",wx.getStorageSync("init_num"))
    // if(this.data.inint_num===null){
    // // 初始化数据
    // this.initialize();
    // }
    // 获取此次用户的openid
    var _openid = wx.getStorageSync("_openid");
    that.setData({
      openid: _openid,
      // inint_num:this.data.inint_num*1+1,
    })
    that.getmessage();
    this.getData()
  }, 

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () { 
    //获得popup组件
    this.popup = this.selectComponent("#popup");
  },

  showPopup() {
    this.popup.showPopup();
  },
  _error() {
    console.log('取消：');
    this.popup.hidePopup();
  },
  //确认事件
  _success() {
    console.log('确定：');
    this.popup.hidePopup();
    wx.navigateTo({
      url: '../jobs/jobs',
    })
  },

  //新的一天
  async new_day(){
    console.log("new day start")
    //获取当前时间
    var time = util.formatDate(new Date());
    console.log('当前日期:' + time);
    //上次时间登陆
    var lasttime = wx.getStorageSync("lasttime");
    console.log('上次登陆:' + lasttime);
    var countID = wx.getStorageSync("countID");
    //如果日期变更，重置数据
    if (time != lasttime || lasttime === '') {
      this.setData({ lasttimee: util.formatDate(new Date())})
      console.log('新的一天！');
      console.log("new_day更新数据前的数据："+this.data.day_word);
      wx.setStorageSync("lasttime", time)
      wx.setStorageSync("all_num", 0)
      wx.setStorageSync("word_record", '');
      wx.setStorageSync("now_num",0);
      wx.setStorageSync("first_init",0);
      wx.setStorageSync("daka",'打卡');
      wx.setStorageSync("init_num",null);
      console.log("new_day更新数据后的数据："+this.data.day_word);
      console.log("new_day now num:" ,wx.getStorageSync("now_num"));
      db.collection('userData').where({
        _openid: this.data.openid
      }).get({
        success: res => {
          //console.log("运行了1234", res)
          if (res.data.length == 1) {
            //console.log("运行了123", res.data[0]._id)
            db.collection('userData').doc(res.data[0]._id).update({
              data: {
                username: this.data.username,
                all_num: 0,
                word_record:[],
                now_num: 0,
                lasttime: time,
                first_init:0,
                daka:'打卡',
              },
              success: res => {
                console.log('新的一天更新数据成功', res)
              },
              fail: err => {
                icon: 'none',
                  wx.showToast({
                    title: '更新数据失败',
                  })
                console.error('[数据库] [更新记录] 失败：', err)
              }
            })
          }
        }
      })

      this.onLoad();
    }
    var now_num = wx.getStorageSync("now_num");
    var all_num = wx.getStorageSync("all_num");
    var day_num = wx.getStorageSync("dayNum");
    var id = wx.getStorageSync("previous");
    var checked = wx.getStorageSync("checked");
    const word_record = wx.getStorageSync("word_record");
    const collection = wx.getStorageSync("collection")
    const day_word = wx.getStorageSync("day_word");
    console.log("new_day setData数据前的数据："+this.data.day_word);
    this.setData({
      id: id,
      checked: checked,
      day_num: day_num,
      all_num: all_num,
      word_record: word_record,
      day_word: day_word,
      now_num: now_num,
      collection: collection
    })
    console.log("new_day setData数据后的数据："+this.data.day_word);
    console.log('今天已学:' + this.data.now_num);
    console.log('当前书已学:' + this.data.id);
  },

  async run(){
    const initialize=await this.initialize()
    console.log(initialize)
    const new_day=await this.new_day()
  },
  /**
   * 生命周期函数--监听页面显示
   */
   onShow: function () {
      this.run()
     this.get_num()
  },

  // 将缓存中的用户数据记录到数据库
  getData: function () {
    //获取当前时间
    console.log("更新开始")
    var time = util.formatDate(new Date());
    console.log("have=", this.data.have)
    // 查询当前用户的数据是否存在数据库
    db.collection('userData').where({
      _openid: this.data.openid
    }).get({
      success: res => {
        console.log("getData123:", res)
        if (res.data.length == 0) {
          console.log("zoule")
          db.collection('userData').add({
            data: {
              username: this.data.username,
              id: this.data.id,
              checked: this.data.checked,
              day_num: this.data.day_num,
              all_num: this.data.all_num,
              word_record: this.data.word_record,
              collection: this.data.collection,
              now_num: this.data.now_num,
              day_word: null,
              lasttime: time,
              max_num:0,
              img: wx.getStorageSync('img'),
              record:[],
            },
            success: res => {
              // 在返回结果中会包含新创建的记录的 _id
              this.setData({
                countId: res._id,
                have: 1,
              })
              wx.showToast({
                title: '新增记录成功',
              })
              console.log('[数据库] [新增记录] 成功，记录 _id: ', res)

            },
            fail: err => {
              wx.showToast({
                icon: 'none',
                title: '新增记录失败'
              })
              console.error('[数据库] [新增记录] 失败：', err)
            }
          })
        // } else {
        //   // 获取缓存中最后一次登陆时间
        //   var time2 = wx.getStorageSync("lasttime");
        //   console.log("time2:", time2);
        //   console.log("更新数据前的数据1："+wx.getStorageSync("day_word"))
        //   db.collection('userData').doc(this.data.countID).update({
        //     data: {
        //       username: this.data.username,
        //       id: this.data.id,
        //       checked: this.data.checked,
        //       day_num: this.data.day_num,
        //       all_num: this.data.all_num,
        //       word_record: this.data.word_record,
        //       collection: this.data.collection,
        //       day_word: this.data.day_word,
        //       now_num: this.data.now_num,
        //       lasttime: time2,
        //       img: wx.getStorageSync('img')
        //     },
        //     success: res => {
        //       console.log('更新数据成功', res)
        //       console.log("更新数据后的数据1："+this.data.day_word);
        //       console.log("now day now num:" ,wx.getStorageSync("now_num"));
        //       console.log("更新数据结束")
        //     },
        //     fail: err => {
        //       icon: 'none',
        //         wx.showToast({
        //           title: '更新数据失败',
        //         })
        //       console.error('[数据库] [更新记录] 失败：', err)
        //     }
        //   })

        }
        this.setData({
          have: res.data.length,
          countId: res.data._id,

        })
        console.log('[数据库] [查询记录] 成功: ', res.data.length)
      },
      fail: err => {
        this.setData({
          have: 0
        })
        console.error('[数据库] [查询记录] 失败：', err)
      }
    })


  },

  // 将用户的数据从数据库读取初始化
  async initialize() {
    console.log("初始化开始")
    return new Promise((resolve,reject)=>{
          // let p= new Promise(function(resolve,reject){
       // 获取此次用户的openid
    var _openid = wx.getStorageSync("_openid");
    console.log("初始化用到的openid:"+_openid);
    // 获取数据库中用户的应用数据
    db.collection('userData').where({
      _openid: _openid,
    }).get({
      success: res => {
        console.log("初始化的callback",res)
        var _id = res.data[0]._id;
        console.log("初始化setData数据前的数据："+this.data.day_word);
        this.setData({
          username: res.data[0].username,
          id: res.data[0].id,
          checked: res.data[0].checked,
          day_word:res.data[0].day_word,
          day_num: res.data[0].day_num,
          all_num: res.data[0].all_num,
          word_record: res.data[0].word_record,
          collection: res.data[0].collection,
          now_num: res.data[0].now_num,
          lasttime: res.data[0].lasttime,
          record:res.data[0].record,
          daka:res.data[0].daka,
          daka_day:res.data[0].daka_day,
          countID:res.data[0]._id,
        })
        console.log("初始化setData数据后的数据："+this.data.day_word);
        console.log("初始化的回调函数",res)
        console.log("初始化更新数据前的数据："+this.data.day_word);
        wx.setStorageSync("previous", res.data[0].id)
        wx.setStorageSync("all_num", res.data[0].all_num)
        wx.setStorageSync("word_record", res.data[0].word_record);
        wx.setStorageSync("now_num", res.data[0].now_num);
        wx.setStorageSync("collection", res.data[0].collection)
        wx.setStorageSync("dayNum", res.data[0].day_num)
        wx.setStorageSync("day_word", this.data.day_word)
        wx.setStorageSync("checked", res.data[0].checked)
        if (this.data.lasttimee!= util.formatDate(new Date())){
        wx.setStorageSync("lasttime", res.data[0].lasttime)
        }
        wx.setStorageSync("max_num", res.data[0].max_num)
        wx.setStorageSync("record",res.data[0].record)
        wx.setStorageSync("daka",this.data.daka)
        wx.setStorageSync("daka_day",this.data.daka_day)
        wx.setStorageSync("countID",this.data.countID)
        console.log("初始化更新数据后的数据："+this.data.day_word);
        console.log("初始化结束")
        resolve("初始化")
      }
    
    })
    })
    // })
    // return p
   
  },

  getmessage: function () {
    // 获取此次用户的openid
    var _openid = wx.getStorageSync("_openid");
    // 获取数据库中用户的信息
    const cont = db.collection('usermessage');
    cont.where({
      _openid: _openid,
    }).get({
      success: res => {
        var username = res.data[0].username;
        this.setData({
          username: username,
        })
        console.log("用户数据:", this.data.username);
      }
    })

    // 获取数据库中用户的应用数据
    db.collection('userData').where({
      _openid: _openid,
    }).get({
      success: res => {
        console.log("查询返回值", res)
        var _id = res.data[0]._id;
        this.setData({
          countID: _id,
        })
        console.log("用户数据3:", this.data.countID);
      }
    })
  },
    //获取单词书的数量
  get_num:function () {
    var checked = wx.getStorageSync("checked")
    if(checked===''||checked == undefined){
      this.setData({
        checked_show: '还未设置任务~'
      })
    }
    switch (checked) {
      case 'cet4': this.setData({ list_num: list2.wordList.length,
      checked_show:'四级词书'
      }); break;
      case 'cet6': this.setData({ list_num: list3.wordList.length,
      checked_show:'六级词书'
      }); break;
      case '考研': this.setData({ list_num: list4.wordList.length,
      checked_show:'考研词书'
      }); break;
      case 'cet4高频': this.setData({ list_num: list5.wordList.length,
      checked_show:'四级高频'
      }); break;
      case 'cet6高频': this.setData({ list_num: list6.wordList.length,
      checked_show:'六级高频'
      }); break;
      case '考研高频': this.setData({ list_num: list7.wordList.length,
      checked_show:'考研高频'
      }); break;
  }
},

  

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    wx.setStorageSync("init_num",this.data.inint_num);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },

})